<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/25
 * Time: 15:42
 */

namespace app\api\model;


use think\Model;
use think\db;

class Trip extends Model
{
    public function createCustomMadeByTemplate($temp_id,$admin_id)
    {
        $trip = db('trip')->find($temp_id);
        if(empty($temp_id) || empty($trip)) return '模板不存在';
        if(empty($trip['is_template'])) return '禁止非模板行程导入';

        unset($trip['id'],$trip['is_template']);
        $schedules = db('schedule')->where('groupid',$temp_id)->select();
        if(!empty($schedules)){
            $schedule_ids = array_column($schedules,'id');
            $actives = db('active')->where(['groupid'=>['in',$schedule_ids]])->select();
            //封装日程和poi
            foreach ($schedules as $key=>$value){
                $schedules[$key]['children'] = [];
                foreach ($actives as $k=>$v){
                    if($v['groupid']==$value['id']){
                        unset($v['id']);
                        $schedules[$key]['children'][] = $v;
                        unset($actives[$k]);
                    }
                }
            }
        }
        db::startTrans();
        try{
            $trip['adminid'] = $admin_id;
            $trip['name'] = $trip['name']."_copy_".date("Y-m-d");
            $trip['create_time'] = time();
            db('trip')->insert($trip);
            $newTripId = db('trip')->getLastInsID();

            if(!empty($schedules)){
                foreach ($schedules as $key=>$value){
                    $newActives = $value['children'];
                    unset($value['id'],$value['children']);
                    $value['groupid'] = $newTripId;
                    $value['create_time'] = time();
                    db('schedule')->insert($value);
                    $sid = db('schedule')->getLastInsID();
                    $value['update_time'] = time();
                    foreach ($newActives as $active){
                        $active['groupid'] = $sid;
                        $active['create_time'] = time();
                        $active['update_time'] = time();
                        db('active')->insert($active);
                    }
                }
            }

            db::commit();
            return ['msg'=>'模板使用成功','data'=>['id'=>$newTripId]];
        }catch (Exception $e){
            db::rollback();
            return json_encode($e->getMessage());
        }
    }
}